package servlet;

import Dao.JdbcTools;
import Dao.UserMapper;
import model.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;

@WebServlet("/DelUser")
public class StuDel extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1,获取删除的那一条记录的id
        String id = req.getParameter("id");
        System.out.println(id);
        //2.调用Dao层的删除api进行删除操作


//            int del = JdbcTools.del("delete from student where id=?", id);
        //调用数据访问层
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
//从配置文件中获取一个工厂对象
        SqlSessionFactory fac = new SqlSessionFactoryBuilder().build(in);
//通过工厂获取sqlsession对象
        SqlSession sqlSession = fac.openSession();
//sqlsession对象执行映射mapper文件中的sql语句
        UserMapper mapper=sqlSession.getMapper(UserMapper.class);
        System.out.println("Integer.valueOf(id) = " + Integer.valueOf(id));
        int i = mapper.delUser(Integer.valueOf(id));
        sqlSession.commit();

        System.out.println("i = " + i);
        if (i> 0) {
                System.out.println(id);
                //删除成功之后，重新获取数据，动态生成前端页面
                    //获取数据库中展示数据
                    List<Student> stulist = mapper.getUserById();
                    //数据展示 servlet
                    req.setAttribute("stulist", stulist);
                    req.getRequestDispatcher("showlist").forward(req, resp);
        }
    }
}
